package com.bus.admin.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bus.admin.bean.Orderbus;
import com.bus.admin.bean.PayRequest;
import com.bus.admin.controller.helper.$;
import com.bus.admin.controller.model.ApiResultModel;
import com.bus.admin.util.AuthSign;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.result.BaseWxPayResult;
import com.sun.org.apache.regexp.internal.RE;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @项目名称: bus-admin
 * @包名称: com.bus.admin.controller
 * @创建人员: Mr.Administrator  张子艺
 * @创建时间: 2020-04-20 10:34
 * @版本:
 */
@Controller
@RequestMapping("/pay/return")
@Slf4j
public class PayReturnController extends BaseController {
    @Value("${ali.pay.APP_ID}")
    String APP_ID;
    @Value("${ali.pay.APP_PRIVATE_KEY}")
    String APP_PRIVATE_KEY;
    @Value("${ali.pay.CHARSET}")
    String CHARSET;
    @Value("${ali.pay.ALIPAY_PUBLIC_KEY}")
    String ALIPAY_PUBLIC_KEY;
    @Value("${ali.pay.is_prod}")
    String is_prod;

    @RequestMapping("/payTest")
    @ResponseBody
    public ApiResultModel<Object> payTest(String moeny) {
        return $.success((Object) aliPayService.createOrder(moeny));
    }

    @RequestMapping("/payTestAliPayH5")
    @ResponseBody
    public ApiResultModel<Object> payTestAliPayH5(@RequestBody PayRequest payRequest, HttpServletRequest request) {
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) {
            return $.error("token不能为空");
        }
        Orderbus orderbus = getOrder(payRequest, AuthSign.verifyToken(token).get("userId").toString());
        if (orderbus == null) {
            return $.error("订单异常");
        }
        return $.success((Object) aliPayService.createH5Order(payRequest, orderbus));
    }

    @RequestMapping("/payTestWechat")
    @ResponseBody
    public ApiResultModel<Object> payTestWechat(String moeny) {
        return $.success((Object) busWxPayService.createOrder(moeny));
    }

    @RequestMapping("/payTestWechatPayH5")
    @ResponseBody
    public ApiResultModel<Object> payTestWechatPayH5(String moeny, HttpServletRequest request) {
        System.out.println(request.getHeader("token"));
        return $.success((Object) busWxPayService.createH5Order(moeny));
    }


    private Orderbus getOrder(PayRequest payRequest, String userId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("userid", userId);
        if (payRequest.getAttach().equals("定金")) {
            queryWrapper.eq("dingjinNum", payRequest.getOrdernum());
            return orderbusService.getOne(queryWrapper);
        }
        if (payRequest.getAttach().equals("尾款")) {
            queryWrapper.eq("weikuanNum", payRequest.getOrdernum());
            return orderbusService.getOne(queryWrapper);
        }
        if (payRequest.getAttach().equals("全款")) {
            queryWrapper.eq("ordernum", payRequest.getOrdernum());
            return orderbusService.getOne(queryWrapper);
        }
        return null;
    }

    @RequestMapping(value = "/aliPay")
    public String aliPay(HttpServletRequest request) {

        System.out.println("阿里支付宝回掉");
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        System.out.println(params);
//切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
//boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        boolean flag = false;
        try {
            flag = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, "RSA2");
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if (flag) {
            System.out.println("验签成功");
            //获取自己的参数
     Map map= JSONObject.parseObject(params.get("passback_params").toString(),Map.class);
            buessRrturn(params.get("out_trade_no").toString(),map.get("payType").toString(),new BigDecimal(params.get("total_amount").toString()));
        }
        return "";
    }
private  void  buessRrturn(String orderNum,String orderType,BigDecimal totalFree){
        Orderbus orderbus=null;
        QueryWrapper queryWrapper=new QueryWrapper();


    if (orderType.equals("定金")) {
        queryWrapper.eq("dingjinNum", orderNum);
        orderbus= orderbusService.getOne(queryWrapper);
        BigDecimal oldPayMoeny=new BigDecimal(orderbus.getPayMoney());
        orderbus.setPayMoney(oldPayMoeny.add(totalFree).toString());
        orderbus.setPayStatus(2);
        orderbus.setStatus(2);
        orderbus.setPaytime1(System.currentTimeMillis()+"");
        orderbus.setPayType(0);
        orderbusService.updateById(orderbus);
    }
    if (orderType.equals("尾款")) {
        queryWrapper.eq("weikuanNum", orderNum);
        orderbus= orderbusService.getOne(queryWrapper);
        BigDecimal oldPayMoeny=new BigDecimal(orderbus.getPayMoney());
        orderbus.setPayMoney(oldPayMoeny.add(totalFree).toString());
        orderbus.setStatus(2);
        orderbus.setPayStatus(2);
        orderbus.setPayType(0);
        orderbus.setPaytime3(System.currentTimeMillis()+"");
        orderbusService.updateById(orderbus);
    }
    if (orderType.equals("全款")) {
        queryWrapper.eq("ordernum", orderNum);
        orderbus= orderbusService.getOne(queryWrapper);
        BigDecimal oldPayMoeny=new BigDecimal(orderbus.getPayMoney());
        orderbus.setPayMoney(oldPayMoeny.add(totalFree).toString());
        orderbus.setStatus(2);
        orderbus.setPayStatus(2);
        orderbus.setPayType(1);
        orderbus.setPaytime2(System.currentTimeMillis()+"");
        orderbusService.updateById(orderbus);
    }
}
    @RequestMapping(value = "/weChatPay")
    public String weChatPay(HttpServletRequest request, HttpServletResponse response) {
        try {
            String xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
            WxPayOrderNotifyResult result = wxPayService.parseOrderNotifyResult(xmlResult);
            System.out.println(result.getAttach());
            // 加入自己处理订单的业务逻辑，需要判断订单是否已经支付过，否则可能会重复调用
            String orderId = result.getOutTradeNo();
            String tradeNo = result.getTransactionId();
            String totalFee = BaseWxPayResult.fenToYuan(result.getTotalFee());
            return WxPayNotifyResponse.success("处理成功!");
        } catch (Exception e) {
            log.error("微信回调结果异常,异常原因{}", e.getMessage());
            return WxPayNotifyResponse.fail(e.getMessage());
        }
    }

}
